import _ from 'lodash'
const moment = require('moment')

/**
 * 日期格式化
 * @param fmt 格式字符串
 * @param date 日期对象，默认当前时间
 * @returns {string}
 *
 * format('yyyy-MM-dd hh:mm:ss.SSSSSS') 2006-07-02 08:09:04.423000
 * format('yyyy-MM-dd hh:mm:ss.SSS') 2006-07-02 08:09:04.423
 * format('yyyy-M-d h:m:s.S) 2006-7-2 8:9:4.18
 */
const format = (fmt = 'yyyy-MM-dd hh:mm:ss', date = null) => {
  if (_.isNull(date)) {
    date = new Date()
  }

  const o = {
    'y+': date.getFullYear(),
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    'S+': date.getMilliseconds()
  }

  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      const match = RegExp.$1
      let v = '00' + o[k]
      let start = v.length - match.length
      let end = v.length

      if (k === 'S+') {
        v = o[k] + '000000'
        start = 0
        end = match.length
      }

      fmt = fmt.replace(
        match,
        match.length === 1 ? o[k] : v.substr(start, end)
      )
    }
  }

  return fmt
}

/**
 * 日期格式化
 * @param dateTime date 格式
 * @returns {string}
 * 2020-09-01
 */
function dateToStr(dateTime) {
  const year = dateTime.getFullYear()
  let month = dateTime.getMonth() + 1
  let day = dateTime.getDate()
  if (month < 10) {
    month = '0' + month
  }
  if (day < 10) {
    day = '0' + day
  }
  return year + '-' + month + '-' + day
}

/**
 * 日期格式化
 * @param time 14位时间戳
 * @returns {string}
 *
 * time(1598889600) 2020-09-01 00:00:00
 */
function timestampToStr(time) {
  const date = new Date(time + 8 * 3600 * 1000) // 增加8小时
  return date.toJSON().substr(0, 19).replace('T', ' ')
}

function strToTimestamp(strTime) {
  const date = new Date(strTime) // 增加8小时
  return date.getTime()
}

function getHistoryStrTime(strTime, beforeDay) {
  const date = new Date(Date.parse(strTime.replace(/-/g, '/')))
  date.setDate(date.getDate() - beforeDay)
  return dateToStr(date)
}

function getHistoryTimeStamp(strTime, beforeDay) {
  const date = new Date(Date.parse(strTime.replace(/-/g, '/')))
  date.setDate(date.getDate() - beforeDay)
  return date.getTime()
}

function getLastWeekDay(day) {
  return moment().week(moment().week() - 1).endOf('week').day(day).format('YYYY-MM-DD')
}

export { format, timestampToStr, strToTimestamp, getHistoryStrTime, dateToStr, getHistoryTimeStamp, getLastWeekDay }
